package online.flowerinsnow.minecraft.bukkit.manhunt.command;

import online.flowerinsnow.minecraft.bukkit.manhunt.util.CommandUtils;
import online.flowerinsnow.minecraft.bukkit.manhunt.util.MessageUtils;
import org.bukkit.Bukkit;
import org.bukkit.command.Command;
import org.bukkit.command.CommandSender;
import org.bukkit.command.TabExecutor;
import org.bukkit.entity.Player;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;

import java.util.ArrayList;
import java.util.List;

public class CommandPing implements TabExecutor {
    @Override
    public boolean onCommand(@NotNull CommandSender sender, @NotNull Command command, @NotNull String label, @NotNull String[] args) {
        if (args.length == 0) {
            if (!(sender instanceof Player)) {
                MessageUtils.sendMustBePlayer(sender);
                return true;
            }
            if (CommandUtils.checkPermission(sender, "manhunt.ping.self")) return true;
            Player player = (Player) sender;
            player.sendMessage(MessageUtils.parseColor("&7[&b!&7]&b您的延迟是: " + getColorPing(player.getPing()) + "&bms"));
            return true;
        } else if (args.length == 1) {
            if (CommandUtils.checkPermission(sender, "manhunt.ping.other")) return true;
            Player player = Bukkit.getPlayer(args[0]);
            if (player == null) {
                sender.sendMessage(MessageUtils.parseColor("&7[&c×&7]&c玩家不在线"));
                return true;
            }
            sender.sendMessage(MessageUtils.parseColor("&7[&b!&7]&e" + player.getName() + "&b 的延迟是: " + getColorPing(player.getPing()) + "&bms"));
            return true;
        } else {
            sender.sendMessage(MessageUtils.parseColor("&7[&a?&7]&b用法: &e/ping [玩家]"));
            return true;
        }
    }

    @Nullable
    @Override
    public List<String> onTabComplete(@NotNull CommandSender sender, @NotNull Command command, @NotNull String alias, @NotNull String[] args) {
        if (args.length == 1 && sender.hasPermission("manhunt.ping.other")) {
            return CommandUtils.playerSubCommandFilter(sender, args[0]);
        }
        return new ArrayList<>();
    }

    private String getColorPing(int ping) {
        char color;
        if (ping <= 0) color = '2';
        else if (ping < 100) color = 'a';
        else if (ping < 200) color = 'e';
        else if (ping < 300) color = 'c';
        else color = '4';
        return "§" + color + ping;
    }
}
